package indi.yangshenhui.hbase.dao.util;

import indi.yangshenhui.hbase.dao.exception.HBaseDaoException;
import indi.yangshenhui.tool.ObjectUtil;
import indi.yangshenhui.tool.StringUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 
 * @author yangshenhui
 */
public class FieldUtil {

	public static <T> Object getFieldValue(T t, Field field)
			throws HBaseDaoException {
		if (ObjectUtil.isNull(t) || ObjectUtil.isNull(field)) {
			return null;
		}
		try {
			String prefix = (field.getType() == Boolean.TYPE)
					|| (field.getType() == Boolean.class) ? "is" : "get";
			String methodName = prefix
					+ StringUtil.initialsCapital(field.getName());
			Method method = t.getClass().getMethod(methodName);
			return method.invoke(t, new Object[0]);
		} catch (Exception e) {
			throw new HBaseDaoException(e);
		}
	}

	public static <T> void setFieldValue(T t, Field field, byte[] value)
			throws HBaseDaoException {
		if (ObjectUtil.isNull(t) || ObjectUtil.isNull(field)) {
			return;
		}
		if (ObjectUtil.isNull(value)) {
			return;
		}
		try {
			String methodName = "set"
					+ StringUtil.initialsCapital(field.getName());
			Method method = t.getClass().getMethod(methodName, field.getType());
			method.invoke(t, TypeUtil.transform(value, field.getType()));
		} catch (Exception e) {
			throw new HBaseDaoException(e);
		}
	}

	private FieldUtil() {
	}

}